<template>
  <view class="inventory-query-container">
    <!-- 渐变背景头部 -->
    <view class="header-gradient">
      <view class="header-content">
        <text class="back-btn" @click="goBack">←</text>
        <text class="header-title">库存查询</text>
        <text class="header-subtitle">Stock Inquiry</text>
      </view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-card">
        <view class="search-input-wrapper">
          <input 
            class="search-input" 
            v-model="searchKey" 
            placeholder="搜索物料编码/名称/规格" 
            @confirm="handleSearch"
          />
          <text class="search-icon" @click="handleSearch">🔍</text>
        </view>
        <view class="filter-tags">
          <view 
            class="tag" 
            :class="{ active: currentFilter === 'all' }" 
            @click="changeFilter('all')"
          >
            <text>全部</text>
          </view>
          <view 
            class="tag" 
            :class="{ active: currentFilter === 'low' }" 
            @click="changeFilter('low')"
          >
            <text>低库存</text>
          </view>
          <view 
            class="tag" 
            :class="{ active: currentFilter === 'high' }" 
            @click="changeFilter('high')"
          >
            <text>高库存</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-card">
          <view class="stat-icon">📊</view>
          <view class="stat-content">
            <text class="stat-number">{{ totalItems }}</text>
            <text class="stat-label">物料种类</text>
          </view>
        </view>
        <view class="stat-card">
          <view class="stat-icon">⚖️</view>
          <view class="stat-content">
            <text class="stat-number">{{ totalWeight }}吨</text>
            <text class="stat-label">总重量</text>
          </view>
        </view>
        <view class="stat-card">
          <view class="stat-icon">📦</view>
          <view class="stat-content">
            <text class="stat-number">{{ totalQuantity }}</text>
            <text class="stat-label">总数量</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 库存列表 -->
    <scroll-view class="inventory-list" scroll-y @scrolltolower="loadMore">
      <view class="list-header">
        <text class="header-title">库存明细</text>
        <view class="sort-options" @click="showSortPicker = true">
          <text class="sort-text">{{ sortOptions[sortIndex] }}</text>
          <text class="sort-arrow">▼</text>
        </view>
      </view>

      <view v-if="inventoryList.length === 0" class="empty-state">
        <view class="empty-icon">📋</view>
        <text class="empty-title">暂无库存数据</text>
        <text class="empty-desc">请先添加物料信息</text>
      </view>

      <view class="inventory-grid">
        <view 
          class="inventory-card" 
          v-for="(item, index) in inventoryList" 
          :key="index"
          @click="showDetail(item)"
        >
          <view class="card-header">
            <text class="material-name">{{ item.name }}</text>
            <view 
              class="stock-status" 
              :class="getStockStatusClass(item.availableStock)"
            >
              {{ getStockStatusText(item.availableStock) }}
            </view>
          </view>

          <view class="card-content">
            <view class="info-row">
              <text class="info-label">编码：</text>
              <text class="info-value">{{ item.code }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">规格：</text>
              <text class="info-value">{{ item.spec }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">库位：</text>
              <text class="info-value">{{ item.location }}</text>
            </view>
          </view>

          <view class="card-footer">
            <view class="stock-info">
              <text class="stock-label">库存：</text>
              <text class="stock-value">{{ item.availableStock }} {{ item.unit }}</text>
            </view>
            <view class="weight-info">
              <text class="weight-label">重量：</text>
              <text class="weight-value">{{ item.weight }}吨</text>
            </view>
          </view>

          <view class="progress-bar">
            <view 
              class="progress-fill" 
              :style="{ width: getProgressWidth(item.availableStock, item.maxStock) }"
            ></view>
          </view>
        </view>
      </view>

      <view v-if="loading" class="loading-more">
        <text class="loading-text">加载中...</text>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="action-buttons">
        <view class="btn btn-export" @click="exportData">
          <text class="btn-icon">📊</text>
          <text class="btn-text">导出</text>
        </view>
        <view class="btn btn-scan" @click="scanCode">
          <text class="btn-icon">📷</text>
          <text class="btn-text">扫码</text>
        </view>
        <view class="btn btn-add" @click="addMaterial">
          <text class="btn-icon">➕</text>
          <text class="btn-text">添加</text>
        </view>
      </view>
    </view>

    <!-- 排序选择器 -->
    <u-picker 
      :show="showSortPicker" 
      :columns="[sortOptions]" 
      @confirm="onSortConfirm"
      @cancel="showSortPicker = false"
    />

    <!-- 详情弹窗 -->
    <u-popup 
      :show="showDetailPopup" 
      mode="bottom" 
      @close="showDetailPopup = false"
    >
      <view class="detail-popup">
        <view class="popup-header">
          <text class="popup-title">库存详情</text>
          <text class="close-btn" @click="showDetailPopup = false">✕</text>
        </view>
        
        <scroll-view class="popup-content" scroll-y>
          <view class="detail-info">
            <view class="detail-section">
              <text class="section-title">基本信息</text>
              <view class="info-grid">
                <view class="info-item">
                  <text class="label">物料名称</text>
                  <text class="value">{{ selectedMaterial.name }}</text>
                </view>
                <view class="info-item">
                  <text class="label">物料编码</text>
                  <text class="value">{{ selectedMaterial.code }}</text>
                </view>
                <view class="info-item">
                  <text class="label">规格型号</text>
                  <text class="value">{{ selectedMaterial.spec }}</text>
                </view>
                <view class="info-item">
                  <text class="label">存放库位</text>
                  <text class="value">{{ selectedMaterial.location }}</text>
                </view>
              </view>
            </view>

            <view class="detail-section">
              <text class="section-title">库存信息</text>
              <view class="stock-grid">
                <view class="stock-item">
                  <text class="label">总库存</text>
                  <text class="value">{{ selectedMaterial.totalStock }} {{ selectedMaterial.unit }}</text>
                </view>
                <view class="stock-item">
                  <text class="label">可用库存</text>
                  <text class="value">{{ selectedMaterial.availableStock }} {{ selectedMaterial.unit }}</text>
                </view>
                <view class="stock-item">
                  <text class="label">冻结库存</text>
                  <text class="value">{{ selectedMaterial.frozenStock }} {{ selectedMaterial.unit }}</text>
                </view>
                <view class="stock-item">
                  <text class="label">总重量</text>
                  <text class="value">{{ selectedMaterial.weight }}吨</text>
                </view>
              </view>
            </view>

            <view class="detail-section">
              <text class="section-title">预警信息</text>
              <view class="warning-info">
                <view class="warning-item" v-if="selectedMaterial.availableStock < selectedMaterial.minStock">
                  <text class="warning-icon">⚠️</text>
                  <text class="warning-text">库存低于安全库存，建议补货</text>
                </view>
                <view class="warning-item" v-if="selectedMaterial.availableStock > selectedMaterial.maxStock">
                  <text class="warning-icon">⚡</text>
                  <text class="warning-text">库存过高，建议调整采购计划</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="popup-actions">
          <view class="btn btn-adjust" @click="adjustStock">
            <text class="btn-text">调整库存</text>
          </view>
          <view class="btn btn-record" @click="viewRecord">
            <text class="btn-text">查看记录</text>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKey: '',
      currentFilter: 'all',
      sortIndex: 0,
      sortOptions: ['按库存排序', '按名称排序', '按重量排序'],
      inventoryList: [],
      selectedMaterial: {},
      showSortPicker: false,
      showDetailPopup: false,
      loading: false,
      page: 1,
      hasMore: true
    }
  },
  computed: {
    totalItems() {
      return this.inventoryList.length
    },
    totalWeight() {
      return this.inventoryList.reduce((total, item) => {
        return total + (Number(item.weight) || 0)
      }, 0).toFixed(2)
    },
    totalQuantity() {
      return this.inventoryList.reduce((total, item) => {
        return total + (Number(item.availableStock) || 0)
      }, 0)
    }
  },
  onLoad() {
    this.loadInventoryData()
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    handleSearch() {
      this.page = 1
      this.loadInventoryData()
    },
    changeFilter(filter) {
      this.currentFilter = filter
      this.page = 1
      this.loadInventoryData()
    },
    onSortConfirm(e) {
      this.sortIndex = e.indexs[0]
      this.showSortPicker = false
      this.sortInventoryList()
    },
    loadInventoryData() {
      // 模拟库存数据
      const mockData = [
        {
          id: 1,
          name: '螺纹钢 HRB400',
          code: 'MAT001',
          spec: 'Φ12*12000',
          location: 'A1-01',
          totalStock: 1500,
          availableStock: 1200,
          frozenStock: 300,
          weight: 18.5,
          unit: '件',
          minStock: 500,
          maxStock: 2000
        },
        {
          id: 2,
          name: '螺纹钢 HRB400',
          code: 'MAT002',
          spec: 'Φ16*12000',
          location: 'A1-02',
          totalStock: 2000,
          availableStock: 1800,
          frozenStock: 200,
          weight: 25.2,
          unit: '件',
          minStock: 800,
          maxStock: 2500
        },
        {
          id: 3,
          name: '盘螺 HRB400',
          code: 'MAT003',
          spec: 'Φ8*1000',
          location: 'B2-01',
          totalStock: 800,
          availableStock: 750,
          frozenStock: 50,
          weight: 4.8,
          unit: '件',
          minStock: 300,
          maxStock: 1000
        },
        {
          id: 4,
          name: '角钢 Q235',
          code: 'MAT004',
          spec: '50*50*5',
          location: 'C3-01',
          totalStock: 300,
          availableStock: 280,
          frozenStock: 20,
          weight: 3.7,
          unit: '件',
          minStock: 100,
          maxStock: 500
        },
        {
          id: 5,
          name: '工字钢 Q235',
          code: 'MAT005',
          spec: '20#',
          location: 'D4-01',
          totalStock: 120,
          availableStock: 100,
          frozenStock: 20,
          weight: 12.5,
          unit: '件',
          minStock: 50,
          maxStock: 200
        }
      ]
      
      let filteredData = mockData
      
      // 搜索过滤
      if (this.searchKey) {
        filteredData = mockData.filter(item => 
          item.name.includes(this.searchKey) ||
          item.code.includes(this.searchKey) ||
          item.spec.includes(this.searchKey)
        )
      }
      
      // 库存状态过滤
      if (this.currentFilter === 'low') {
        filteredData = filteredData.filter(item => item.availableStock < item.minStock)
      } else if (this.currentFilter === 'high') {
        filteredData = filteredData.filter(item => item.availableStock > item.maxStock)
      }
      
      this.inventoryList = filteredData
      this.hasMore = false
    },
    loadMore() {
      if (!this.hasMore || this.loading) return
      
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.hasMore = false
      }, 1000)
    },
    sortInventoryList() {
      const sortType = this.sortOptions[this.sortIndex]
      switch(sortType) {
        case '按库存排序':
          this.inventoryList.sort((a, b) => b.availableStock - a.availableStock)
          break
        case '按名称排序':
          this.inventoryList.sort((a, b) => a.name.localeCompare(b.name))
          break
        case '按重量排序':
          this.inventoryList.sort((a, b) => b.weight - a.weight)
          break
      }
    },
    showDetail(item) {
      this.selectedMaterial = item
      this.showDetailPopup = true
    },
    getStockStatusClass(stock) {
      if (stock < 100) return 'status-low'
      if (stock > 1000) return 'status-high'
      return 'status-normal'
    },
    getStockStatusText(stock) {
      if (stock < 100) return '低库存'
      if (stock > 1000) return '高库存'
      return '正常'
    },
    getProgressWidth(current, max) {
      return Math.min((current / max) * 100, 100) + '%'
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          this.searchKey = res.result
          this.handleSearch()
        },
        fail: () => {
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    },
    exportData() {
      uni.showModal({
        title: '导出数据',
        content: '确定要导出当前库存数据吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '导出成功',
              icon: 'success'
            })
          }
        }
      })
    },
    addMaterial() {
      uni.navigateTo({
        url: '/pages/smart/warehouse/in-warehouse/create'
      })
    },
    adjustStock() {
      uni.showToast({
        title: '库存调整功能开发中',
        icon: 'none'
      })
    },
    viewRecord() {
      uni.showToast({
        title: '库存记录功能开发中',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.inventory-query-container {
  height: 100vh;
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  display: flex;
  flex-direction: column;
}

.header-gradient {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  padding: 40rpx 30rpx 20rpx;
  border-radius: 0 0 40rpx 40rpx;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  font-size: 36rpx;
  color: #fff;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 40rpx;
  font-weight: 700;
  color: #fff;
  margin-right: auto;
  margin-left: 20rpx;
}

.header-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.search-section {
  padding: 30rpx 30rpx 0;
}

.search-card {
  background: #fff;
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.search-input-wrapper {
  position: relative;
  margin-bottom: 20rpx;
}

.search-input {
  width: 100%;
  background: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 50rpx;
  padding: 20rpx 60rpx 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 36rpx;
  color: #666;
}

.filter-tags {
  display: flex;
  gap: 20rpx;
}

.tag {
  padding: 12rpx 24rpx;
  background: #f8f9fa;
  border-radius: 50rpx;
  font-size: 24rpx;
  color: #666;
  transition: all 0.3s ease;
}

.tag.active {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  color: #fff;
}

.stats-section {
  padding: 0 30rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.stat-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.stat-icon {
  font-size: 48rpx;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.inventory-list {
  flex: 1;
  padding: 0 30rpx;
  overflow-y: auto;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.header-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 12rpx 20rpx;
  background: #f8f9fa;
  border-radius: 50rpx;
}

.sort-text {
  font-size: 24rpx;
  color: #666;
}

.sort-arrow {
  font-size: 20rpx;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 20rpx;
}

.empty-icon {
  font-size: 100rpx;
  opacity: 0.5;
}

.empty-title {
  font-size: 32rpx;
  color: #666;
  font-weight: 500;
}

.empty-desc {
  font-size: 24rpx;
  color: #999;
}

.inventory-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20rpx;
}

.inventory-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.material-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.stock-status {
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 20rpx;
  font-weight: 500;
}

.status-low {
  background: #ffe6e6;
  color: #ff4757;
}

.status-normal {
  background: #e6f7ff;
  color: #1890ff;
}

.status-high {
  background: #e6ffe6;
  color: #52c41a;
}

.card-content {
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
}

.info-label {
  font-size: 24rpx;
  color: #666;
  width: 100rpx;
}

.info-value {
  font-size: 24rpx;
  color: #333;
  flex: 1;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.stock-info, .weight-info {
  display: flex;
  align-items: center;
}

.stock-label, .weight-label {
  font-size: 24rpx;
  color: #666;
}

.stock-value, .weight-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.progress-bar {
  height: 8rpx;
  background: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  transition: width 0.3s ease;
}

.loading-more {
  text-align: center;
  padding: 30rpx;
}

.loading-text {
  font-size: 24rpx;
  color: #999;
}

.bottom-bar {
  background: #fff;
  padding: 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 50rpx;
  text-align: center;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.btn-export {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.btn-scan {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  color: #fff;
}

.btn-add {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  color: #fff;
}

.btn-icon {
  font-size: 28rpx;
}

.btn-text {
  font-size: 24rpx;
}

.detail-popup {
  background: #fff;
  border-radius: 40rpx 40rpx 0 0;
  max-height: 80vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  padding: 20rpx;
}

.popup-content {
  padding: 30rpx;
  max-height: 60vh;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 40rpx;
}

.detail-section {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.info-grid, .stock-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.info-item, .stock-item {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.label {
  font-size: 24rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.warning-info {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.warning-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx;
  background: #fff7e6;
  border-radius: 12rpx;
}

.warning-icon {
  font-size: 32rpx;
}

.warning-text {
  font-size: 24rpx;
  color: #333;
}

.popup-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.btn-adjust {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  color: #fff;
}

.btn-record {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}
</style>